<template>
  <view class="container">
    <!--    <scroll-view scroll-y="true" @scrolltolower="lower()">-->
    <view class="container-top">
      <u-swiper
          :list="bannerList"
          keyName="url"
          @click="bannerClick"
          indicator
          indicatorMode="line"
          circular
      ></u-swiper>
    </view>

    <view class="container-bottom-wrap">
      <view class="container-bottom">
        <u-sticky offset-top="100rpx">
          <view class="search-wrap">
            <view @click="getLocation" class="search-city">
              {{ cityName }}
              <u-icon name="arrow-down" color="#000" size="15"></u-icon>
            </view>
            <view class="search-input">
              <u--input
                  v-model="fullAddress"
                  @confirm="handleSearchConfirm"
                  placeholder="请输入小区或商圈名称"
                  :customStyle="{textIndent: '20rpx'}"
                  border="bottom"
                  clearable
              ></u--input>
            </view>
          </view>
        </u-sticky>


        <view class="house-recommend">
          <view class="recommend-title">
            房源推荐
          </view>
          <view class="recommend-contents">
            <!--          <scroll-view scroll-y="true" @scrolltolower="lower()" :style="{'max-width':`90%`, 'height':scrollH+'px'}">-->
<!--            <scroll-view style="min-height: 100vh" scroll-y="true" @scrolltolower="lower()">-->
            <scroll-view  scroll-y="true" @scrolltolower="lower()">

              <!--            {{ infoList }}-->
              <template v-for="(info, index) in infoList">
<!--                <navigator :url="`/subpages/houseinfo/houseinfo?id=${info.id}`" hover-class="navigator-hover">-->
                  <view @click="goPage(`/subpages/houseinfo/houseinfo?id=${info.id}`)" class="house-info">
                    <view class="info-pic-warp">
                      <image class="info-pic" :src="getImageUrl(info.imgUrls)"></image>
                    </view>
                    <view class="info-detail">
                      <view class="detail-title">
                        {{ info.title }}
                      </view>
                      <view class="detail-feature">
                        <text v-if="info.decoration" style="visibility: unset" class="detail-feature-decoration">{{ info.decoration }}</text>
                        <text v-if="!info.decoration" style="visibility: hidden" class="detail-feature-decoration">{{ info.decoration }}</text>
                      </view>
                      <view class="detail-price">
                        {{ info.price }}
                        <text class="price-unit">元/月</text>
                      </view>
                    </view>
                  </view>
<!--                </navigator>-->
              </template>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>

    <!--    </scroll-view>-->
  </view>

</template>

<script>

import {getBannerList, getHouseInfoList, getLocationCity} from "@/config/api";
import GetCity from "@/components/getCity.vue";
import {getImageUrl, goPage} from "@/config/util/common";

export default {
  components: {
    GetCity
  },
  data() {
    return {
      bannerList: [
        // 'https://cdn.uviewui.com/uview/swiper/swiper3.png',
        // 'https://cdn.uviewui.com/uview/swiper/swiper2.png',
        // 'https://cdn.uviewui.com/uview/swiper/swiper1.png',
      ],

      cityName: "成都",
      ak: 'vHlWIzGYtdWW3aSSENUInGt4actfQBFX', // 百度地图 替换为你的API Key
      // 总条数
      total: 0,
      // 房源出租信息（大部分数据来自安居客）表格数据
      infoList: [],
      pageNum: 1,
      pageSize: 10,
      fullAddress: '', //房源完整地址

    }
  },
  mounted() {


  },
  onReachBottom() {  //上拉触底函数
    // uni.$u.toast("已下拉")

    const nextPage = this.pageNum + 1;//每次上拉请求新的一页
    if ((this.total + this.pageSize) <= (nextPage * this.pageSize)) {
      uni.$u.toast("无更多信息")
      return
    }

    this.pageNum = nextPage;
    uni.showLoading({title: "加载中..."})
    this.requestHouseInfoList().then(res => {
      uni.hideLoading();

      this.infoList = this.infoList.concat(res.rows);
      this.total = res.total;

    }).catch(err => {
      uni.hideLoading();
    })
  },

  onShow() {

    // uni.navigateTo({
    //   url: "/pages/test/test"
    // })

    //检查app 网络
    uni.getNetworkType({
      success: function (res) {
        console.log(res.networkType);
        if (res.networkType === "none") {
          uni.redirectTo({
            url: '/pages/networknone/networknone'
          });
        }
      }
    });

    (async () => {
      //获取当前城市
      var city = uni.getStorageSync('city');
      if (this.cityName === city) {
        return;
      }
      if (city) {
        // uni.$u.toast(this.city)
        this.cityName = city;

      } else {

        await getLocationCity().then(({cityName}) => {
          // debugger
          uni.setStorageSync('city', cityName);
          this.cityName = cityName;
        })


        // // #ifdef H5
        // await getLocationCity().then(cityName => {
        //   // debugger
        //   uni.setStorageSync('city', cityName);
        //   this.cityName = cityName;
        // })
        //
        // // #endif
        //
        //
        // // #ifndef H5
        // await this.getLocationCity().then(content => {
        //   let cityName = content.address_detail.city.replace("市", "");
        //   // uni.$u.toast(cityName)
        //   uni.setStorageSync('city', cityName);
        //   uni.setStorageSync('locationInfo', content);
        //   this.cityName = cityName;
        //   uni.$u.toast(this.cityName)
        // })
        // // #endif
      }

      //请求房源信息列表
      this.pageNum = 1;
      this.requestHouseInfoList().then(res => {
        this.infoList = res.rows;
        this.total = res.total;
        this.pageNum = 1;
      });
    })();


    // uni.showToast({
    //   title: JSON.stringify(mapData),
    //   icon: 'none',
    //   duration: 10000
    //
    // });

  },
  onPullDownRefresh() {
    console.log('refresh');
    // setTimeout(function () {
    //   uni.stopPullDownRefresh();
    // }, 1000);

    //请求房源信息列表
    this.pageNum = 1;
    this.requestHouseInfoList().then(res => {
      this.infoList = res.rows;
      this.total = res.total;
      this.pageNum = 1;

      uni.stopPullDownRefresh();
    });
  },
  onLoad() {
    let _that = this;

    //获取轮播图
    getBannerList({
      orderByColumn: "banner_sort_index",
      isAsc: "desc"
    }).then(res => {
      // uni.$u.toast("获取成功")

      _that.bannerList = res.rows.map(item => {

        return {
          ...item,
          url: _that.$baseFileUrl + item.bannerImgUrl
        }
      })
    });


    //请求房源信息列表
    this.requestHouseInfoList().then(res => {
      this.infoList = res.rows;
      this.total = res.total;
    });

  },
  onUnload() {
    // 页面销毁时移除监听器
    // uni.$off('postMessage');
  },
  computed: {

    scrollH: function () {
      let sys = uni.getSystemInfoSync();
      let winWidth = sys.windowWidth;
      let winrate = 750 / winWidth;
      let winHeight = parseInt(sys.windowHeight * winrate)
      return winHeight

    }
  },
  methods: {
    goPage,
    getImageUrl,

    //执行搜索确认
    handleSearchConfirm(value) {

      //请求房源信息列表
      this.requestHouseInfoList().then(res => {
        this.infoList = res.rows;
        this.total = res.total;
        this.pageNum = 1;
      });

    },
    //请求房源信息列表
    requestHouseInfoList() {
      return new Promise((resolve, reject) => {
        return getHouseInfoList({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderByColumn: "create_time",
          isAsc: "desc",
          city: uni.getStorageSync('city') ? uni.getStorageSync('city') : this.cityName,
          fullAddress: this.fullAddress,
        }).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    lower(e) {
      console.log("已经滚动到底部了")
    },
    getLocation() {
      uni.navigateTo({
        url: '/subpages/searchcity/searchcity'
      })
    },
    handleMap() {
      uni.navigateTo({
        // url: "/pages/test/test"
        url: "/pages/baidumap/baidumap"
        // url: "/pages/transform/transform"
      })
    },
    getLocationCity() {
      return new Promise((resolve, reject) => {
        uni.request({
          // url: 'http://api.map.baidu.com/location/ip?ak=LB3tfoRl9qw23PHpIoQQabmFsGM39EEK&coor=bd09ll',
          url: 'http://api.map.baidu.com/location/ip?ak=LB3tfoRl9qw23PHpIoQQabmFsGM39EEK',
          method: 'GET',
          success: (res) => {
            console.log("-----------地址：", res);

            if (res.data.status === 0) {
              resolve(res.data.content)
              return
            }
            reject(res.data.status)
            // https://api.map.baidu.com/location/ip?ip=%s&ak=%s
          }
        });
      })
    },
    bannerClick(index) {
      if (this.bannerList[index].bannerRedirectLink) {
        uni.navigateTo({
          url: "/pages/webview/webview?url=" + this.bannerList[index].bannerRedirectLink
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">

.container {
  //position: relative;
  justify-content: unset;
  flex-direction: column;
  //min-height: 100.1vh;
  //min-height:101vh;


  .container-top {
    width: 100%;
  }

  .container-bottom-wrap {
    width: 100%;
  }

  .container-bottom {
    width: calc(100% - ($sys-padding-30 + $sys-padding-30));
    padding-left: $sys-padding-30;
    padding-right: $sys-padding-30;
    display: flex;
    flex-direction: column;

    .search-wrap {
      //position: -webkit-sticky;
      //position: sticky;
      //top: 0; /* 距顶部的距离 */
      //z-index: 10; /* 确保sticky元素在最上层 */

      //background-color: #fff;
      //padding: 10px;

      //width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      border-radius: 5rem;
      transform: translateY(-50%);
      padding: 10rpx;
      box-shadow: 0px 0px 20px 5px rgba(0, 0, 0, 0.3);
      background-color: white;

      .search-city {
        width: 30%;
        display: flex;
        justify-content: space-evenly;
        border-right: 1px solid $sys-color-grey-170;
        align-items: center;

      }

      .search-input {
        width: 70%;
      }
    }

    .house-recommend {

      .recommend-title {
        font-weight: bolder;
      }

      .recommend-contents {

        .house-info {
          display: flex;
          border-bottom: 1px solid $sys-color-grey-170;
          padding-top: $sys-padding-30;
          padding-bottom: $sys-padding-30;

          .info-pic-warp {
            padding-right: $sys-padding-30;

            .info-pic {
              width: 250rpx;
              height: 150rpx;
            }
          }

          .info-detail {
            font-size: 13px;

            .detail-title {
              font-weight: bolder;
            }

            .detail-feature {

              font-size: 12px;

              .detail-feature-decoration {
                background-color: rgb(230, 246, 254);
                color: rgb(129, 211, 248);
                padding: 5rpx;
              }
            }

            .detail-price {
              color: $sys-color-pink-weight;

              .price-unit {
                font-size: 15px;
                color: $sys-color-pink-weight;
              }
            }
          }
        }
      }
    }


  }


}

</style>
